package com.example.chessbattleplatform.web.StorageIo.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chessbattleplatform.Pojo.AppConfig;
import com.example.chessbattleplatform.Pojo.Exception.BusinessException;
import com.example.chessbattleplatform.Pojo.Exception.StatusCode;
import com.example.chessbattleplatform.utils.GetLocalDateTimeUtils;
import com.example.chessbattleplatform.web.StorageIo.CopyUtils.CopyFileUtils;
import com.example.chessbattleplatform.web.StorageIo.Pojo.Mapper.FileStorage;
import com.example.chessbattleplatform.web.StorageIo.Pojo.Vo.FileLimitVo;
import com.example.chessbattleplatform.web.StorageIo.Pojo.Vo.UploadFileVo;
import com.example.chessbattleplatform.web.StorageIo.mapper.FileMapper;
import com.example.chessbattleplatform.web.StorageIo.service.impl.FileServiceInterface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class FileService extends ServiceImpl<FileMapper, FileStorage> implements FileServiceInterface {

    private final FileMapper fileMapper;
    private final AppConfig appConfig;
    private final CopyFileUtils cpyFileUtils;


    @Override
    public UploadFileVo uploadFile(MultipartFile file) {

        // 2025-3-27
        String uploadFormat = GetLocalDateTimeUtils.GetLocalDateTimeToString();

        // 获取上传目录 + 加上时间
        System.out.println(uploadFormat);
        Path uploadPath = Path.of(new File(appConfig.getUploadPath() + "/" + uploadFormat).getAbsolutePath());
        //获取原始文件名 - 1.jpg  123.0.0.jpg
        String originalFilename = file.getOriginalFilename();
        //构造唯一的文件名 (不能重复) - uuid(通用唯一识别码) de49685b-61c0-4b11-80fa-c71e95924018
        //时间(当前时间) + uuid(通用唯一识别码)=组合成新的文件名 2025-3-27:de49685b-61c0-4b11-80fa-c71e95924018
        UUID uuid = UUID.randomUUID();
        //  构造唯一的文件名
        //  String newFileName = uuid + "_" + originalFilename;
        String newFileName = uploadFormat + "-" + uuid;
        // 创建目录
        if (!Files.exists(uploadPath)) {
            try {
                Files.createDirectory(uploadPath);
                System.out.println("目录创建成功");
            } catch (Exception e) {
                System.err.println("创建目录失败: " + e.getMessage());
            }
        }

        // 保存文件到上传目录
        Path filePath = uploadPath.resolve(newFileName);
        log.info("文件上传位置 {}", filePath);

        //添加到数据库
        FileStorage fileStorage = FileStorage.builder().fileId(newFileName).name(originalFilename).type(new MimetypesFileTypeMap().getContentType(originalFilename)).path(filePath.toString()).build();


        if (fileMapper.insert(fileStorage) <= 0) {
            throw new BusinessException(StatusCode.ERROR_CODE, "文件上传失败");
        }

        // 保存文件到上传目录
        try {
            file.transferTo(filePath.toFile());
        } catch (IOException e) {
            throw new BusinessException(StatusCode.ERROR_CODE, "文件上传失败: " + e.getMessage());
        }

        //返回数据
        return cpyFileUtils.FileStorageToUploadFileVo(fileStorage);
    }

    @Override
    public FileLimitVo InquireFile(int Current, int limit) {
        // 创建 分页查询 类 第 page 页，每页limit 条数据。
        Page<FileStorage> page1 = new Page<>(Current, limit);
        // 使用 分页查询
        Page<FileStorage> productPage = fileMapper.selectPage(page1, null);
        // 获取查询结果
        List<FileStorage> fileStorages = productPage.getRecords();

        ArrayList<UploadFileVo> uploadFileVos = new ArrayList<>();

        fileStorages.forEach(fileStorage -> {
            uploadFileVos.add(cpyFileUtils.FileStorageToUploadFileVo(fileStorage));
        });

        //productPage.getPages() 总页码数
        //productPage.getSize() 每页显示的商品数量
        //productPage.getCurrent() 当前页码
        return new FileLimitVo(uploadFileVos, productPage.getPages(), productPage.getCurrent(), productPage.getSize());
    }


    @Override
    public FileStorage selectByFileId(String fileId) {
        LambdaQueryWrapper<FileStorage> last = new LambdaQueryWrapper<FileStorage>().eq(FileStorage::getFileId, fileId);

        return fileMapper.selectOne(last);
    }


    @Override
    public boolean deleteFile(String fileId) {
        LambdaQueryWrapper<FileStorage> wrapper = new LambdaQueryWrapper<FileStorage>().eq(FileStorage::getFileId, fileId);
        FileStorage fileStorage = fileMapper.selectOne(wrapper);

        if (fileStorage.getPath() != null) {
            Path path = Path.of(fileStorage.getPath());
            if (path.toFile().exists()) {
                log.error(path.toFile().delete() ? "文件删除成功" : "文件删除失败");
            }
        }
        return fileMapper.delete(wrapper) > 0;
    }
}
